<?php defined('SYSPATH') or die('No direct script access.');

/**
 *
 * @author pahhan
 */
class Task_Parser_Load extends Minion_Task
{
    protected $_options = array(
        'id' => NULL,
        'count' => 1,
    );

    public function build_validation(Validation $validation)
    {
        return parent::build_validation($validation)
            ->rule('id', 'not_empty') // Require this param
            ->rule('id', 'numeric') // This param should be numeric
            ->rule('count', 'numeric'); // This param should be numeric
    }

    private function _execute_body(Model_DataLoader $dl, $count, Log_LoadingLogger $logger)
    {
        for ($i = 0; $i < $count; $i++)
        {
            $result = $dl->load();

            if( $result === FALSE )
            {
                $msg = sprintf('Loader return FALSE at %d iteration', $i+1);
                $logger->write(array($msg));
                print $msg.PHP_EOL;
                $i = $count;
            }
            else
            {
                $msg = sprintf('Message with id=%s is loaded', $result);
                $logger->write(array($msg));
                print $msg.PHP_EOL;
            }
        }
    }

    protected function _execute(array $params)
    {
        $id = $params['id'];
        $count = $params['count'];

        $logger = new Log_LoadingLogger(DOCROOT.'logs/loads');
        $logger->write(array(sprintf('Loading started for parser %d, count %d', $id, $count)));

        $pi = ORM::factory('ParseInfo', $id);
        if( !$pi->id ) throw new Exception(sprintf('ParseInfo with id=%s not found', $id));

        if( $pi->is_active )
        {
            $logger->write(array(sprintf('Parser with id=%s is already active', $id)));
            throw new Exception(sprintf('ParseInfo with id=%s is already active', $id));
        }

        $factory = new Model_Loader_LoaderFactory();
        $dl = $factory->create($pi);

        $pi->is_active = true;
        $pi->save();
        try
        {
            $this->_execute_body($dl, $count, $logger);
        }
        catch(Exception $e)
        {
            $msg = sprintf('Exception %d: %s', $e->getCode(), $e->getMessage()).PHP_EOL;
            $logger->write(array($msg));
            print $msg;
            $pi->is_active = false;
            $pi->save();
            return;
        }

        $pi->is_active = false;
        $pi->save();

        $logger->write(array("Loading finished\n"));
    }

}

